package com.xiang.utils;

import com.xiang.config.EsConfig;
import org.elasticsearch.action.search.*;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;

/**
 * 滚动查询
 *
 * @author xiangtianlei@gogpay.cn
 * @date 2023-01-30
 */
public class ScrollQuery {
    RestHighLevelClient client = EsConfig.getClient();
    Logger logger = LoggerFactory.getLogger(RangeQuery.class);

    /**
     * 滚动查询
     */
    @Test
    public void scrollQuery() throws IOException {
        // 创建request
        SearchRequest request = new SearchRequest("user");
        // 指定生存时间
        request.scroll(TimeValue.timeValueMinutes(1));
        // 封装查询条件
        SearchSourceBuilder builder = new SearchSourceBuilder();
        // 每次数据查询200条
        builder.size(300);
        builder.sort("age", SortOrder.ASC);
        builder.query(QueryBuilders.matchAllQuery());
        request.source(builder);
        // 执行查询结果
        SearchResponse res = client.search(request, RequestOptions.DEFAULT);
        // 获取scrollId
        String scrollId = res.getScrollId();
        int i = 1;
        logger.info("----------------------------当前正在查看第1页的数据---------------------------------------------");
        for (SearchHit hit : res.getHits().getHits()) {
            logger.info("首页数据:{}", hit.getSourceAsMap());
        }
        // 模拟分页查询
        while (true) {
            // 创建searchScrollRequest
            SearchScrollRequest scrollRequest = new SearchScrollRequest(scrollId);
            // 指定生存时间内
            scrollRequest.scroll(TimeValue.timeValueMinutes(1));
            // 获取执行获取返回结果
            SearchResponse scrollRes = client.scroll(scrollRequest, RequestOptions.DEFAULT);
            // 判断是否查询到数据
            SearchHit[] hits = scrollRes.getHits().getHits();
            if (hits != null && hits.length > 0) {
                i = i + 1;
                logger.info("----------------------------当前正在查看第{}页的数据---------------------------------------------", i);
                for (SearchHit hit : hits) {
                    logger.info("查询结果：{}", hit.getSourceAsMap());
                }
            } else {
                // 没有数据退出
                logger.info("----------------------------到底了---------------------------------------------");
                break;
            }
        }
        // 删除scrollId
        ClearScrollRequest clearScrollRequest = new ClearScrollRequest();
        // 指定scrolld
        clearScrollRequest.addScrollId(scrollId);
        // 删除
        ClearScrollResponse clearScrollResponse = client.clearScroll(clearScrollRequest, RequestOptions.DEFAULT);
        // 输出结果
        logger.info("删除输出结果：{}", clearScrollResponse.isSucceeded());

    }

}
